const query = require('../db/query')
const path = require('path')
const fs = require('fs')
const dbpath = path.join('/Users/HUAWEI/Desktop/study-99/zuoye1002/app/db','/user.json')
//增
const addUserService = async(params)=>{
    console.log(params , 'params');
    let mydata = await JSON.parse(fs.readFileSync(dbpath),'utf-8')
    mydata.push(params)
    await fs.writeFileSync(dbpath,JSON.stringify(mydata),'utf-8')
    return true
}

//查
const getUserService = async(params)=>{
    let mydata = await JSON.parse(fs.readFileSync(dbpath),'utf-8')
    return mydata
}

//删
const delUserService = async(params)=>{
    let mydata = await JSON.parse(fs.readFileSync(dbpath),'utf-8')
    let arr=[]
    await mydata.forEach(item => {
        if(item.id != params){
            arr.push(item)
        }
    })
    await fs.writeFileSync(dbpath,JSON.stringify(arr),'utf-8')
    return true
}

//修改
const updataUserService = async (params) => {
    console.log(params,'params')
    //读取所有的数据
    let mydata = await JSON.parse(fs.readFileSync(dbPath), 'utf-8')
    //循环所有数据
    await mydata.forEach(item => {
        //如果id是要修改的数据
        if (item.id == params) {
            item.username = params.username
        }
    })
    await fs.writeFileSync(dbPath, JSON.stringify(mydata), 'utf-8')
    return true
}




//查看
const getList=async(params)=>{
    const sql = `select*from users`
    const result = await query(sql)
    return result
}
//添加
const addList = async(params)=>{
    const sql = `insert into users(username,pwd,age,phone,nickname) values('${params.username}','${params.pwd}','${params.age}','${params.phone}','${params.nickname}')`
    // console.log(sql);
    const result = await query(sql)
    console.log(result,'result1');
    if(result.affectedRows == 1){
        return true
    }else {
        return false
    }
}

//删除
const delList = async(params)=>{
    const sql = `delete from users where id='${params.id}'`
    // console.log(sql);
    const result = await query(sql)
    console.log(result,'result2');
    if(result.affectedRows == 1){
        return true
    }else {
        return false
    }
}
//修改
const updataList = async(params)=>{
    const sql = `update users set age='${params.age}',phone='${params.phone}' where id='${params.id}'`
    // console.log(sql);
    const result = await query(sql)
    console.log(result,'result3');
    if(result.affectedRows == 1){
        return true
    }else {
        return false
    }
}
module.exports={
    getList,
    addList,
    delList,
    updataList,
    addUserService,
    getUserService,
    delUserService,
    updataUserService
}